package com.apartment.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 缓存Aspect
 * @author sxy
 * @date
 */
@Aspect
@Component
public class CacheAspect {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 先从缓存中取数据，如果缓存中有，直接使用
     * 如果缓存中没有数据，再调用目标方法，执行数据库操作
     * @param joinPoint
     * @return
     */

    @Around("@annotation(com.apartment.common.annotation.CacheSelect)")
    public Object around(ProceedingJoinPoint joinPoint){

        String key = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        StringBuffer buffer = new StringBuffer(methodName);
        Object[] args = joinPoint.getArgs();
        for(Object arg:args){
            buffer.append(arg);
        }

        String field = buffer.toString();

        HashOperations hashOperations = redisTemplate.opsForHash();

        Object value = hashOperations.get(key, field);

        //缓存中有数据，直接使用缓存中的数据
        if(value!=null){
            return value;
        }
        try {
            Object result = joinPoint.proceed();
            hashOperations.put(key,field,result);

            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException("发送");
        }
    }
    /**
     * 清除缓存 增删改查使用
     * @param joinPoint
     */
    @After("@annotation(com.apartment.common.annotation.CacheClear)")
    public void after(JoinPoint joinPoint){
        String className = joinPoint.getTarget().getClass().getName();
        redisTemplate.delete(className);
    }
}
